<template>
  <el-form
    :model="user"
    status-icon
    :rules="rules"
    ref="user"
    label-width="100px"
    class="demo-ruleForm"
  >
    <h1 >注册</h1>
    <el-form-item label="账号" prop="userName">
      <el-input v-model.number="user.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        type="password"
        v-model="user.password"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input
        type="password"
        v-model="user.checkPass"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('user')">注册</el-button>
      <el-button @click="resetForm">重置</el-button>
        <router-link to="/login">已有账号，立即登录</router-link>
    </el-form-item>
  </el-form>
</template>

<script>
  
  export default {
  
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.user.password !== '') {
            this.$refs.user.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.user.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    
      return {
         user:{},
        rules: {
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        }
      };
    },
    methods: {
     async   registerUser(){
            const {data}  = await  this.$api.register.registerUser(this.user)
            console.log(data);
             if(data.code){
                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  });
                        this.$router.push('/login')
             }else{
                 this.$message.error('注册失败');
             }
        },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              this.registerUser()
          
          } else {
                  this.$message.error('注册失败');
            return false;
          }
     
        });
      },
      resetForm() {
         this.user={}
      }
    }
  }
</script>
<style scoped>
.el-form{
    width: 30%;
    height: 400px;
    margin: 100px auto;
    border: 1px solid black;
    padding: 20px;
    box-shadow: 0px 0px 8px 8px grey;
}
h1{
    text-align: center;
}
</style>